//
//  Orderheader.m
//  phmall
//
//  Created by  on 2017/9/8.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "Orderheader.h"

@implementation Orderheader
{
    UIView * _redLine;
    CGFloat itemWidth;
}
-(void)setItems:(NSArray *)items
{
    _items = items;
    //先清空当前视图上的所有子视图
    for (UIView * view in self.subviews) {
        [view removeFromSuperview];
    }
    //添加按钮
    itemWidth = SCREEN_WIDTH/items.count;
    for (int i = 0; i< items.count;i++ ) {
        UIButton * buton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self addSubview:buton];
        [buton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
            make.left.equalTo(self).with.offset(itemWidth*i);
            make.bottom.equalTo(self.mas_bottom).with.offset(2);
            make.width.offset(itemWidth);
        }];
        buton.titleLabel.numberOfLines = 2;
        buton.titleLabel.textAlignment = NSTextAlignmentCenter;
        [buton setTitle:items[i] forState:UIControlStateNormal];
        [buton setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
        [buton setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
        buton.titleLabel.font=[UIFont systemFontOfSize:15];
        [buton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
        buton.tag = Button_Origin_Tag+i;
        
        if (i == 0) {
            buton.selected = YES;
        }
    }
    
    //加红线
    _redLine = [[UIView alloc]init];
    [self addSubview:_redLine];
    [_redLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self).offset(-0);
        make.left.equalTo(self);
        make.width.offset(itemWidth);
        make.height.offset(2);
    }];
    _redLine.backgroundColor = [UIColor orangeColor];

}

-(void)buttonClick:(UIButton*)button
{
    //获取点击的是第几个button
    NSInteger index = button.tag - Button_Origin_Tag;
    [self setSelectAtIndex:index];
    
    //2、把事件传递出去
    if (self.itemClickAtIndex) {
        _itemClickAtIndex(index);
    }
}
-(void)setSelectAtIndex:(NSInteger)index
{
    //1、先调整自身的视图显示
    for (int i = 0; i < self.items.count; i++) {
        UIButton * bt = [self viewWithTag:i+Button_Origin_Tag];

        if (bt.tag-Button_Origin_Tag == index) {
            bt.selected = YES;

        }else{
            bt.selected = NO;
        }
    }
    //调整红线的位置
    [UIView animateWithDuration:0.2 animations:^{
        [_redLine mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self);
            make.left.equalTo(self).with.offset(itemWidth*index);
            make.width.offset(itemWidth);
            make.height.offset(2);
        }];
        [_redLine layoutIfNeeded];
    }];
}

@end
